package com.zdw.zfw.admin.core.jwt;

import cn.hutool.core.bean.BeanUtil;
import com.zdw.zfw.admin.core.util.JwtTokenUtil;
import com.zdw.zfw.admin.modular.system.model.entity.LoginUser;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.Set;

/**
 * 自定义realm
 *
 * @author zdw
 */
public class JwtRealm extends AuthorizingRealm {

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        LoginUser user = (LoginUser) principals.getPrimaryPrincipal();
        Set<String> permissions = user.getPermissions();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        /// 需要角色信息请打开
        // List<SysUserRole> userRoles = user.getUserRoles();
        // simpleAuthorizkationInfo.addRoles(userRoles);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        if (!JwtTokenUtil.checkToken(token)){
            throw new AuthenticationException("token invalid");
        }
        if (JwtTokenUtil.isTokenExpired(token)){
            throw new AuthenticationException("token expired");
        }
        return new SimpleAuthenticationInfo(getUserFromToken(token), token, super.getName());
    }

    /**
     * 从token中获取当前登录用户信息
     *
     * @param token jwt
     * @return 登录用户信息
     */
    private LoginUser getUserFromToken(String token) {
        Claims claimFromToken = JwtTokenUtil.getClaimFromToken(token);
        return BeanUtil.mapToBean((Map<?, ?>) claimFromToken.get("user"), LoginUser.class,false);
    }
}